<?php
namespace Common\Model;
use Common\Model\AiModel;
class CommMcodeModel extends AiModel {
	
	#发送注册验证码
	function registerCode($code, $mobile, $type = true) {
        $r = $this->check_mobile_state($mobile);
        if ($r !== true){
            return $r;
        } else {
            return D('Sms')->sendMessage($mobile,$code);
        }

	}
	
	#发送安全验证码
	function forgetpwd_code($code,$mobile) {
        $r = $this->check_mobile_state($mobile);
        if ($r !== true){
            return $r;
        } else{
            return D('Sms')->sendMessage($mobile,$code);
        }


	}
	
	#创建验证码
	function getCode($mobile) {

        $code = rand(1000, 9999);
        $usinfo = M('User')->where("mobile='{$mobile}'")->find();
        $data = array('mobile'		=> $mobile,
            'code'		=> $code,
            'add_time'	=> ADD_TIME,
            'user_id'		=> (int)$usinfo['id'],
        );
        $had = $this->where("mobile='{$mobile}'")->find();
        if ($had) {
            $this->where("id={$had['id']}")->data($data)->save();
        } else {
            $this->data($data)->add();
        }
        return $code;

	}

	#检测验证码
	function check_code($mobile,$code) {
		$had = $this->where("mobile='{$mobile}' AND code='{$code}' AND add_time>=".(time()-1200) )->find();
		if ($had) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * @param string $mobile
	 * 验证手机号是否可以发短信
	 */
	public function check_mobile_state($mobile=''){
		$ip = ADD_IP;
		#按小时算 1小时1个手机号码5次，ip30次

		$date_state = strtotime(date("Y-m-d",time()));
		$date_end   = $date_state + 86400;

		$date_state2 = time()-3600;
		$date_end2   = time();
		
		#按天判断
		$mobileCount = M('Sms')->where(" mobile = '{$mobile}' AND add_time > $date_state AND add_time < $date_end ")->count();
		if($mobileCount >= 20) return '您今日发送短信的个数已达上限，请明日再发';
		
		$ipCount = M('Sms')->where(" add_ip = '{$ip}' AND add_time > $date_state AND add_time < $date_end ")->count();
		if($ipCount >= 20) return '您今日发送短信的个数已达上限，请明日再发';

		#按小时判断
		$mobileCount = M('Sms')->where(" mobile = '{$mobile}' AND add_time > $date_state2 AND add_time < $date_end2 ")->count();
		$time = M('Sms')->where("mobile = '{$mobile}'")->order('id DESC')->getField('add_time');
		$minus = 60-ceil((ADD_TIME-$time)/60);
		if($mobileCount >= 5) return '您发送短信的个数已达上限，请您'.$minus.'分钟之后再发';

		$ipCount = M('Sms')->where(" add_ip = '{$ip}' AND add_time > $date_state2 AND add_time < $date_end2 ")->count();
		$time = M('Sms')->where("add_ip = '{$ip}'")->order('id DESC')->getField('add_time');
		$minus = 60-ceil((ADD_TIME-$time)/60);
		if($ipCount >= 10) return '您发送短信的个数已达上限，请您'.$minus.'分钟之后再发';

		return true;
	}

}